package terra.model.object.ai;

import terra.managers.ThreadPoolManager;
import terra.model.object.GameObject;
import terra.model.object.LiveObject;
import terra.model.object.action.ActionAttack;
import terra.model.object.action.ActionFollow;
import terra.model.object.action.ActionMove;
import terra.model.object.action.ActionWait;
import terra.model.object.interfaces.Attacker;
import terra.model.runnable.MapIndexChecker;
import terra.util.MathUtil;

public class AttackAI extends NpcAI {

	private static final long serialVersionUID = -2859378917221413850L;

	public int RND_MOVE_CHANCE = 30;
	private LiveObject target;

	@Override
	public void update(int delta) {
		if (getOwner().isDead())
			return;
		if (getCurrentAction() == null)
			think();
		getCurrentAction().update(delta);
		if (getCurrentAction().ended)
			think();

		if (fear > 0)
			if (System.currentTimeMillis() - lastFeared > 10000) {
				fear--;
				lastFeared = System.currentTimeMillis();
			}
	}

	@Override
	public void think() {
		// ищем цель
		checkForTarget();
		// если цель есть
		if (target != null) {
			if (getOwner().distanceTo(target) <= getOwner().getAttackRange())
				setCurrentAction(new ActionAttack(this, target,
						(int) (1000 / getOwner().getStat().getAttackRate())));
			else
				setCurrentAction(new ActionFollow(this, target, getOwner()
						.isAllowJump()));
		} else if (MathUtil.rnd.nextInt(RND_MOVE_CHANCE) == 0) {
			int distance = -100 + MathUtil.rnd.nextInt(200);
			setCurrentAction(new ActionMove(this, distance, getOwner()
					.isAllowJump()));
			if (distance < 0)
				getOwner().setLeft(true);
			else
				getOwner().setLeft(false);
		} else
			setCurrentAction(new ActionWait(this, 250 + MathUtil.rnd.nextInt(250)));

		ThreadPoolManager.getInstance().scheduleGeneral(
				new MapIndexChecker(getOwner(), getOwner().getMapIndex()),
				1000L);
	}

	private void checkForTarget() {
		if (target != null) {
			if (!target.isDead())
				return;
			else
				target = null;
		}
		// если агр - выбираем ближнего врага
		if (isAggressive())
			for (GameObject obj : getOwner().getKnownList().getKnownObjects()
					.values()) {
				LiveObject live = (LiveObject) obj;
				if (target == null)
					target = live;
				if (getOwner().distanceTo(obj) < getOwner().distanceTo(target))
					target = live;
			}
	}

	@Override
	public void isAttacked(Attacker attacker) {
		super.isAttacked(attacker);
		// if (target instanceof LiveObject)
		target = (LiveObject) attacker;
		System.out.println(attacker + " " + target);
		think();

	}

	public LiveObject getTarget() {
		return target;
	}

	public void setTarget(LiveObject target) {
		this.target = target;
	}
}
